<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { QForm, QTable } from '@meetjs/element-plus-kit'

// 使用 文本 替代 Icon
import { tableColumns, formOptions } from './config'
import { getAthleteRewardList, createAthleteReward, updateAthleteReward, deleteAthleteReward } from './api'
import type { RewardRecord } from './types'

interface Props {
	athleteId: string | number | undefined
	data: RewardRecord[]
	readonly?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	readonly: false
})

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)
const tableData = ref<RewardRecord[]>([])
const formRef = ref<FormInstance>()

// 表单数据
const formModel = reactive<Partial<RewardRecord>>({
	infoId: typeof props.athleteId === 'string' ? parseInt(props.athleteId, 10) : props.athleteId,
	rewardTime: '',
	rewardContent: '',
	rewardQuality: '',
	remark: ''
})

// 计算属性
const dialogTitle = computed(() => (isEditing.value ? '编辑奖罚记录' : '新增奖罚记录'))

// 方法
const fetchData = async () => {
	try {
		loading.value = true
		const response = await getAthleteRewardList(props.athleteId!)

		if (response && Array.isArray(response.data)) {
			tableData.value = response.data
		}
	} catch (error) {
		console.error('获取奖罚记录失败:', error)
		ElMessage.error('获取奖罚记录失败')
	} finally {
		loading.value = false
	}
}

const resetForm = () => {
	Object.assign(formModel, {
		infoId: typeof props.athleteId === 'string' ? parseInt(props.athleteId, 10) : props.athleteId,
		rewardTime: '',
		rewardContent: '',
		rewardQuality: '',
		remark: ''
	})

	nextTick(() => {
		formRef.value?.clearValidate()
	})
}

const handleAdd = () => {
	isEditing.value = false
	resetForm()
	dialogVisible.value = true
}

const handleEdit = (row: RewardRecord) => {
	isEditing.value = true
	Object.assign(formModel, { ...row })
	dialogVisible.value = true
}

const handleDelete = async (row: RewardRecord) => {
	try {
		await ElMessageBox.confirm('确定要删除这条奖罚记录吗？', '删除确认', {
			type: 'warning'
		})

		await deleteAthleteReward(row.id!)
		ElMessage.success('删除成功')
		fetchData()
	} catch (error: any) {
		if (error !== 'cancel') {
			console.error('删除奖罚记录失败:', error)
			ElMessage.error('删除失败')
		}
	}
}

const handleSubmit = async () => {
	formRef.value?.validate(async (valid: boolean) => {
		if (!valid) {
			// 验证失败，直接返回，不继续执行API调用
			return
		}

		try {
			submitting.value = true

			if (isEditing.value) {
				await updateAthleteReward(formModel.id!, formModel)
				ElMessage.success('修改成功')
			} else {
				await createAthleteReward(formModel)
				ElMessage.success('新增成功')
			}

			dialogVisible.value = false
			fetchData()
		} catch (error) {
			console.error('提交奖罚记录失败:', error)
			ElMessage.error(isEditing.value ? '修改失败' : '新增失败')
		} finally {
			submitting.value = false
		}
	})
}

const handleClose = () => {
	dialogVisible.value = false
	resetForm()
}

watch(() => props.athleteId, fetchData)

// 暴露方法供父组件调用
defineExpose({
	refreshData: fetchData
})
</script>

<template>
	<div class="reward-record">
		<div class="flex justify-between items-center mb-4">
			<span class="font-semibold text-lg">奖罚情况</span>
			<el-button
				v-if="!readonly"
				type="primary"
				@click="handleAdd"
			>
				+ 新增奖罚
			</el-button>
		</div>

		<QTable
			:data="tableData"
			:columns="tableColumns"
			:loading="loading"
			:pagination="false"
		>
			<template #action="{ row }">
				<el-button
					v-if="!readonly"
					type="primary"
					link
					@click="handleEdit(row)"
				>
					编辑
				</el-button>
				<el-button
					v-if="!readonly"
					type="danger"
					link
					@click="handleDelete(row)"
				>
					删除
				</el-button>
			</template>
		</QTable>

		<!-- 新增/编辑弹窗 -->
		<el-dialog
			v-model="dialogVisible"
			:title="dialogTitle"
			width="800px"
			:before-close="handleClose"
		>
			<QForm
				ref="formRef"
				:model="formModel"
				:form-options="formOptions"
				label-width="100px"
			/>

			<template #footer>
				<div class="flex justify-end">
					<el-button @click="handleClose">取消</el-button>
					<el-button
						type="primary"
						:loading="submitting"
						@click="handleSubmit"
					>
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped lang="scss">
.reward-record {
	padding: 20px;
	background: #ffffff;
	border-radius: 6px;
	box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}
</style>
